const { redisConf, socketConf, serverConf } = require("./config/env");
const { log } = require("./config/utils");
const { redis } = require("./config/redis");

const server = require("http").Server();
const io = require("socket.io")(server, socketConf);

//重置redis状态库！
(async () => {
	await redis.del(redisConf.commonKey);
})();

// 获取当前在线人数
const getClientCounts = async key => {
	const users = await redis.hgetall(key);
	return Object.keys(users).length;
};

io.on("connection", async socket => {
	const sid = socket.id;
	const uid = socket.handshake.query.uid;
	const name = socket.handshake.query.name;
	const ip = socket.handshake.headers["x-real-ip"] || socket.handshake.address || "无";

	const user = await redis.hget(redisConf.commonKey, uid);
	if (!user) {
		log(`[sid: ${sid}] [uid: ${uid}] [up]`, "yellow");
		await redis.hset(redisConf.commonKey, uid, sid);
		io.emit("login", { ip, sid, uid, name });
	}

	io.emit("clientCounts", await getClientCounts(redisConf.commonKey));

	socket.on("logout", async () => {
		const clientCounts = await getClientCounts(redisConf.commonKey);
		io.emit("logout", { ip, sid, uid, name, clientCounts });
		redis.hdel(redisConf.commonKey, uid);
	});

	socket.on("disconnect", async () => {
		log(`[sid: ${sid}] [uid: ${uid}] [down]`, "yellow");
		await redis.hdel(redisConf.commonKey, uid);
		const clientCounts = await getClientCounts(redisConf.commonKey);
		io.emit("logout", { ip, sid, uid, name, clientCounts });
	});

	socket.on("error", (err) => {
		log(err.stack, "red");
	});
});

server.listen(serverConf.port, err => {
	if (err) return console.log(err);
	log(`Socket is running on ${serverConf.port}!`);
});
